package resemClass;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(urlPatterns={"/data"})
public class ConfigJSON extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConfigJSON() {
        super();
        // TODO Auto-generated constructor stub
    }

    public static String jsonres = "";

    public static void setJSON(double[][] res) {
        jsonres = "{ \"cols\": " + ConfigMySQL.cols + ",\"data\": [";
        for (int i = 0; i < ConfigMySQL.cols; i++) {
            for (int j = 0; j < ConfigMySQL.cols; j++) {
                jsonres = jsonres + "\"" + res[i][j] + "\"";
                if (i != ConfigMySQL.cols - 1 || j != ConfigMySQL.cols - 1) {
                    jsonres = jsonres + ",";
                }
            }
        }
        jsonres = jsonres + "]}";
    }

    public static String getJSON() {
        return jsonres;
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/json; charset=utf-8");
        PrintWriter out = response.getWriter();


        try {
            String user = request.getParameter("username");
            double[][] res = ConfigMySQL.getTable("root");
            setJSON(res);
            out = response.getWriter();
            out.println(getJSON());
        } catch (Exception e) {
            out.print("get data error!");
            e.printStackTrace();
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}